package com.jilefojing.web;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.jsoup.Jsoup;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.jilefojing.beans.data.web.response.ArticleData;
import com.jilefojing.beans.data.web.response.DCategoryData;
import com.jilefojing.beans.enums.ItemTypeEnumForSource;
import com.jilefojing.beans.enums.ProgressStatusForSource;
import com.jilefojing.beans.exception.UserContextException;
import com.jilefojing.beans.pojos.RCategorySource;
import com.jilefojing.beans.pojos.Statistics;
import com.jilefojing.beans.pojos.enhanced.EnhancedDCategory;
import com.jilefojing.beans.pojos.enhanced.EnhancedEArticle;
import com.jilefojing.beans.pojos.enhanced.EnhancedStatistics;
import com.jilefojing.beans.vo.Order;
import com.jilefojing.beans.vo.Pagination;
import com.jilefojing.context.beans.vo.UserContext;
import com.jilefojing.service.IDCategoryService;
import com.jilefojing.service.IEArticleService;
import com.jilefojing.service.IRCategorySourceService;
import com.jilefojing.service.IStatisticsService;
import com.jilefojing.util.Detect;
import com.jilefojing.web.base.BaseWeb;
import com.jilefojing.web.convent.CommonConvent;

@Controller
@RequestMapping("article")
public class ArticleWeb extends BaseWeb {
	@Autowired
	private IEArticleService eArticleService;
	@Autowired
	private IStatisticsService statisticsService;
	@Autowired
	private IRCategorySourceService rCategorySourceService;
	@Autowired
	private IDCategoryService dCategoryService;

	@RequestMapping("{id}.html")
	public String toArticlePage(HttpServletRequest request, @PathVariable("id") long id) {

		short sort = 0;
		String sortStr = request.getParameter("sort");
		if (Detect.notEmpty(sortStr)) {
			sort = Short.valueOf(sortStr);
		}

		List<Order> orders = null;
		if (sort == 1) {// 热门
			orders = Arrays.asList(new Order[] { new Order(RCategorySource.COLUMN_HOT_SORT, Order.ORDER_DESC) });
		} else if (sort == 2) {// 最近更新
			orders = Arrays.asList(new Order[] { new Order(RCategorySource.COLUMN_UPDATE_TIME, Order.ORDER_DESC) });
		}

		EnhancedEArticle enhancedEArticle = (EnhancedEArticle) eArticleService.getEnhanced(id, null);
		request.setAttribute("article", CommonConvent.convent2EArticleData(enhancedEArticle));

		enhancedEArticle = eArticleService.appendEnhancedDCategories(enhancedEArticle, null);

		EnhancedDCategory enhancedDCategory = enhancedEArticle.getEnhancedDCategories().get(0);
		enhancedDCategory = dCategoryService.appendEnhancedParentDCategory2EnhancedDCategory(enhancedDCategory, null);

		request.setAttribute("category", CommonConvent.convent2DCategoryData(enhancedDCategory));
		request.setAttribute("description", Jsoup.parse(enhancedEArticle.getContent()).text().replaceAll(">", "").replaceAll("<", ""));

		EnhancedEArticle enhancedPrevEnhancedEArticle = eArticleService.getEnhancedPrevInDCategory(enhancedDCategory, enhancedEArticle.getId(), orders, null);
		request.setAttribute("prevArticle", enhancedPrevEnhancedEArticle);

		EnhancedEArticle enhancedNextEnhancedEArticle = eArticleService.getEnhancedNextInDCategory(enhancedDCategory, enhancedEArticle.getId(), orders, null);
		request.setAttribute("nextArticle", enhancedNextEnhancedEArticle);

		statisticsService.updateCount(ItemTypeEnumForSource.ARTICLE, enhancedEArticle.getId(), Statistics.COLUMN_COUNT_WATCH, true, 1, null);

		return "web/article/article";
	}

	/**
	 * 分页获取的文章列表
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping("list-part.html")
	public String getArticleListPart(HttpServletRequest request) {
		UserContext userContext = null;
		try {
			userContext = super.getUserContext();
		} catch (UserContextException e) {
			// 可忽略
		}

		List<Long> categoryIds = this.getIds(request, "cat");

		short sort = 0;
		String sortStr = request.getParameter("sort");
		if (Detect.notEmpty(sortStr)) {
			sort = Short.valueOf(sortStr);
		}
		int page = 1;
		String pageStr = request.getParameter("page");
		if (Detect.notEmpty(pageStr)) {
			page = Integer.valueOf(pageStr);
			page = page < 1 ? 1 : page;
		}
		short progress = 0;
		String progressStr = request.getParameter("progress");
		if (Detect.notEmpty(progressStr)) {
			progress = Short.parseShort(progressStr);
		}

		// cat=1~2~5-31~3~8 --->两种选择交集
		Pagination<EnhancedEArticle> pagination = new Pagination<EnhancedEArticle>(page, 10, true);
		if (sort == 1) {// 热门
			pagination.addOrder(new Order(RCategorySource.COLUMN_HOT_SORT, Order.ORDER_DESC));
		} else if (sort == 2) {// 最近更新
			pagination.addOrder(new Order(RCategorySource.COLUMN_UPDATE_TIME, Order.ORDER_DESC));
		}
		List<ProgressStatusForSource> progressStatuses = null;
		if (ProgressStatusForSource.getProgressStatusEnumByCode(progress) != null) {
			progressStatuses = Arrays.asList(new ProgressStatusForSource[] { ProgressStatusForSource.getProgressStatusEnumByCode(progress) });
		}

		pagination = eArticleService.getPaginationByCategoryIdsForActive(categoryIds, progressStatuses, pagination, userContext);

		if (Detect.notEmpty(pagination.getItems())) {
			pagination.setItems(eArticleService.appendEnhancedChildren(pagination.getItems(), userContext));
			if (userContext != null) {
				pagination.setItems((List<EnhancedEArticle>) eArticleService.appendEnhancedExtralsForUser(pagination.getItems(), userContext));
			}
			this.resetEnhancedStatistics2NotEntityEnhancedEArticle(pagination.getItems());
			List<ArticleData> articleDatas = CommonConvent.convent2EArticleDatas(pagination.getItems());
			request.setAttribute("articles", articleDatas);
			request.setAttribute("pagination", pagination);
		}

		return "web/article/article_list_part";
	}

	private List<Long> getIds(HttpServletRequest request, String key) {
		String valsStr = request.getParameter(key);
		if (Detect.notEmpty(valsStr)) {
			String[] valStrs = valsStr.split("~");
			List<Long> valIds = new ArrayList<Long>();
			for (String valStr : valStrs) {
				long valLong = Long.valueOf(valStr);
				if (valLong > 0) {
					valIds.add(valLong);
				}
			}
			return valIds;
		}
		return null;
	}

	@RequestMapping("list.html")
	public String toArticleListPage(HttpServletRequest request) {

		UserContext userContext = null;
		try {
			userContext = super.getUserContext();
		} catch (Exception ex) {
			// 可忽略
		}

		Pagination<EnhancedEArticle> pagination = new Pagination<EnhancedEArticle>(1, 10, true);
		pagination.addOrder(new Order(RCategorySource.COLUMN_HOT_SORT, Order.ORDER_DESC));
		pagination = eArticleService.getPaginationByCategoryIdsForActive(null, null, pagination, userContext);

		if (Detect.notEmpty(pagination.getItems())) {
			pagination.setItems(eArticleService.appendEnhancedChildren(pagination.getItems(), userContext));
			if (userContext != null) {
				pagination.setItems((List<EnhancedEArticle>) eArticleService.appendEnhancedExtralsForUser(pagination.getItems(), userContext));
			}
			this.resetEnhancedStatistics2NotEntityEnhancedEArticle(pagination.getItems());

			List<ArticleData> articleDatas = CommonConvent.convent2EArticleDatas(pagination.getItems());
			request.setAttribute("articles", articleDatas);
			request.setAttribute("pagination", pagination);
		}

		List<EnhancedDCategory> enhancedDCategories = eArticleService.getEnhancedDCategories(userContext);
		if (Detect.notEmpty(enhancedDCategories)) {
			List<DCategoryData> dCategoryDatas = CommonConvent.convent2DCategoryDatas(enhancedDCategories);
			request.setAttribute("dCategorys", dCategoryDatas);
		}

		return "web/article/article_list";
	}

	private void resetEnhancedStatistics2NotEntityEnhancedEArticle(List<EnhancedEArticle> enhancedEArticles) {
		for (EnhancedEArticle _EnhancedEArticle : enhancedEArticles) {
			if (!_EnhancedEArticle.isEntity() && Detect.notEmpty(_EnhancedEArticle.getEnhancedChildren())) {
				EnhancedStatistics enhancedStatistics = new EnhancedStatistics();
				enhancedStatistics.setItemType(ItemTypeEnumForSource.ARTICLE);
				for (EnhancedEArticle _childEnhancedEArticle : _EnhancedEArticle.getEnhancedChildren()) {
					if (_childEnhancedEArticle.getEnhancedStatistics() != null) {
						enhancedStatistics.setCountComment(enhancedStatistics.getCountComment() + _childEnhancedEArticle.getEnhancedStatistics().getCountComment());
						enhancedStatistics.setCountWatch(enhancedStatistics.getCountWatch() + _childEnhancedEArticle.getEnhancedStatistics().getCountWatch());
						enhancedStatistics.setCountPraise(enhancedStatistics.getCountPraise() + _childEnhancedEArticle.getEnhancedStatistics().getCountPraise());
						enhancedStatistics.setCountFavorite(enhancedStatistics.getCountFavorite() + _childEnhancedEArticle.getEnhancedStatistics().getCountFavorite());
					}
				}
				_EnhancedEArticle.setEnhancedStatistics(enhancedStatistics);
			}
		}
	}

}
